<script lang="ts" setup>
import { useLayoutInfo } from '@/common/composables/useLayoutInfo'
import { IconPath, PageTitle } from '@/common/constants'
import { checkUserLikeDynamicService, createDynamicCommentService, dynamicCancelLikeService, dynamicLikeService, getDynamicDetailByIdService, getPagedDynamicCommentByIdService } from '@/common/service/dynamic'
import { useUserStore } from '@/common/store'
import type { DynamicComment, DynamicDetail } from '@/common/types/dynamic'
import type { PagedParams } from '@/common/types/request'
import skeleton from '@/common/skeleton/subpack/dynamic-detail.vue'

const { contentAreaHeight, safeBottom } = useLayoutInfo()
const commentValue = ref()

/**
 * 当前动态id
 */
const dynamicId = ref<number>(0)
/**
 * 动态详情
 */
const dynamicDetail = ref<DynamicDetail>()

/**
 * 动态的评论
 */
const dynamicComment = ref<DynamicComment[]>([])

const { hope_user_info } = useUserStore()

/**
 * 根据动态id获取动态详情
 */
const getDynamicDetailById = async () => {
  const { data } = await getDynamicDetailByIdService(dynamicId.value)

  dynamicDetail.value = data
  console.log(data)
}

/**
 * 分页参数
 */
const pagedParams = ref<PagedParams>({
  pageNum: 1,
  pageSize: 5,
})

/**
 * 评论总数
 */
const total = ref<number>(0)

/**
 * 分页获取动态的评论
 */
const getPagedDynamicCommentById = async () => {
  const { data } = await getPagedDynamicCommentByIdService(pagedParams.value, dynamicId.value)
  total.value = data.total
  console.log(data.item)

  if (Array.isArray(data.item)) {
    dynamicComment.value = dynamicComment.value ? dynamicComment.value.concat(data.item) : data.item
  }
}

/**
 * 创建动态评论
 */
const createComment = () => {
  console.log('userAvatarUrl:', hope_user_info?.avatarUrl)
  console.log('user:', hope_user_info)

  const commentData = {
    content: commentValue.value,
    dynamicId: dynamicId.value,
    userAvatarUrl: hope_user_info?.avatarUrl ? hope_user_info.avatarUrl : 'https://hope-mp.oss-cn-guangzhou.aliyuncs.com/2426abd4-ae0d-464a-8298-e5e924248e7d-1732944322974.jpeg',
    userNickname: hope_user_info?.nickname ? hope_user_info.nickname : '',
  }

  dynamicComment.value.unshift({ ...commentData, createTime: new Date().toLocaleString(), id: Math.random() })

  // TODO: 修改参数
  createDynamicCommentService(dynamicId.value, { userAvatarUrl: hope_user_info!.avatarUrl, userNickname: hope_user_info?.nickname, content: commentValue.value }).then(() => {
    showSimpleToast(COMMENT_SUCCESS)

    commentValue.value = ''
  }).catch(() => {
    showSimpleToast(COMMENT_FAIL)
  })
}

/** 用户是否已点赞 */
const isLike = ref<boolean>(false)
/**
 * 动态点赞操作
 */
const onDynamicLike = async () => {
  if (isLike.value) {
    dynamicCancelLikeService(dynamicId.value).then(() => {
      isLike.value = false
    })
    dynamicDetail.value!.likeCount -= 1
    return
  }

  dynamicLikeService(dynamicId.value).then(() => {
    dynamicDetail.value!.likeCount += 1
    isLike.value = true
  })
}

/**
 * 查询用户是否已点赞
 */
const checkUserLikeDynamic = async () => {
  const { data } = await checkUserLikeDynamicService(dynamicId.value)
  isLike.value = data
}

// onShow(() => {
//   Promise.all([getDynamicDetailById(), getPagedDynamicCommentById(), checkUserLikeDynamic()])
// })

onLoad(async (options) => {
  if (!options)
    return
  dynamicId.value = options.dynamicId

  Promise.all([getDynamicDetailById(), getPagedDynamicCommentById(), checkUserLikeDynamic()])
})
</script>

<template>
  <hope-nav-bar :title="PageTitle.DYNAMIC_DETAIL" is-back-icon />

  <scroll-view
    scroll-y class="dynamic-scroll" :style="{
      height: `${contentAreaHeight - safeBottom!}px`,
      paddingBottom: `${safeBottom}px`,
    }"
  >
    <template v-if="dynamicDetail">
      <view class="dynamic-detail-content">
        <uni-title type="h3" :title="dynamicDetail?.title" />
        <!-- 动态作者信息 -->
        <text class="dynamic-detail-info">
          {{ dynamicDetail.createTime }} - {{ dynamicDetail.nickname }}
        </text>
        <view class="dynamic-detail-imgs">
          <image :src="dynamicDetail.imgUrl" mode="aspectFill" class="dynamic-detail-imgs-item" />
        </view>
        <view class="dynamic-detail-text">
          <!-- 动态内容 -->
          {{ dynamicDetail.content }}
        </view>
        <view class="dynamic-like" @click="onDynamicLike">
          <image class="dynamic-like-icon" :src="isLike ? IconPath.LIKE : IconPath.LIKE_GREY" mode="scaleToFill" />
          <!-- 点赞数 -->
          <text
            class="dynamic-like-count" :style="{
              color: isLike ? '#ED4556' : '#999',
            }"
          >
            {{ dynamicDetail.likeCount }}
          </text>
        </view>
      </view>
      <view class="dynamic-comment">
        <view class="dynamic-comment-input">
          <!-- 评论输入框 -->
          <textarea
            v-model="commentValue" class="dynamic-comment-textarea" inputmode="text" confirm-type="send"
            placeholder="文明交流"
          />

          <image class="dynamic-comment-input-send" :src="IconPath.SEND" mode="scaleToFill" @click="createComment" />
        </view>

        <!-- 评论列表 -->
        <view class="dynamic-comment-list">
          <view v-for="comment in dynamicComment" :key="comment.id" class="dynamic-comment-list-item">
            <image :src="comment.userAvatarUrl" mode="aspectFit" class="avatar" />
            <view class="comment">
              <!-- 评论的用户名 -->
              <text class="comment-username">
                {{ comment.userNickname }}
              </text>
              <!-- 评论内容 -->
              <text class="comment-text">
                {{ comment.content }}
              </text>
              <!-- 评论时间 -->
              <text class="comment-create-time">
                {{ comment.createTime }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <skeleton />
    </template>
  </scroll-view>
</template>

<style lang="scss" scoped>
.dynamic {

  &-scroll {
    background-color: $bg-gray;

  }

  &-detail {
    &-content {
      display: flex;
      flex-direction: column;
      padding: 30rpx;
      gap: 20rpx;
      background-color: $color-white;
    }

    &-info {
      font-size: $font-size-sm;
      color: $uni-text-color-grey;
    }

    &-imgs {
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      width: 100%;
      border-radius: $border-radius-base;

      &-item {
        height: 300rpx;
        width: 100%;
        background-color: $color-primary;
      }
    }

    &-text {
      font-size: $font-size-base;
      line-height: 50rpx;
    }
  }

  &-comment {
    margin-top: 30rpx;
    padding-inline: 30rpx;
    padding-block: 50rpx;
    background-color: $color-white;

    &-list {
      display: flex;
      flex-direction: column;
      gap: 30rpx;
      margin-top: 30rpx;

      &-item {
        display: flex;
        gap: 20rpx;

        .avatar {
          width: 100rpx;
          height: 100rpx;
          border-radius: 50%;
        }

        .comment {
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 10rpx;

          &-username {
            font-size: $font-size-base;
            color: $color-primary;
          }

          &-text {
            font-size: $font-size-base;
          }

          &-create-time {
            font-size: $font-size-sm;
            color: $uni-text-color-grey;
          }
        }
      }
    }

    &-textarea {
      width: 100%;
      height: 100%;
      padding-bottom: 80rpx
    }

    &-input {
      position: relative;
      display: flex;
      gap: 40rpx;
      height: 200rpx;
      padding: 30rpx;
      background-color: $bg-gray;
      border-radius: $border-radius-base;

      &-send {
        position: absolute;
        bottom: 30rpx;
        right: 30rpx;
        width: 50rpx;
        height: 50rpx;
        z-index: 999
      }

      &-avatar {
        height: 120rpx;
        width: 120rpx;
        border: 1px solid $color-white;
        border-radius: 50%;
      }
    }

  }

  &-like {
    display: flex;
    flex-direction: column;
    align-self: flex-end;
    gap: 10rpx;

    &-icon {
      width: 50rpx;
      height: 50rpx;
    }

    &-count {
      text-align: center;
      font-size: $font-size-sm;
    }
  }

}
</style>
